/**
 * @author Manoj
 * HTMLParseLister.java
 * This class extends HTMLEditorKit.ParserCallback. It implements various HTML page elemnts handling methods.
 * This class Does the parsing of The Html input file and Puts it into the  two datastructure.
 * 1.HtmlTags : Tag and its properties
 * 2.Tag_parent: tag and its parent.
 * 
 * Modified by Hemant
 * Tagcount is initialized in this class itself using maxid.
 * handleText() method creates displayext objects and put them under current tag
 * It calls createDisplaytextObject() method to create displaytext objects.
 * handleComment() modifies to handle script and comment data also. 
 * Start tag is initialized at start and is returned by getStartTag() method
 */

/*
*Released on 28th June 2008.
*Any violations can be reported at paritosh@wikiocean.net
*What is treated as violations can be found at www.wikiocean.net/ppl1-voilations*
******************************************************************************
* The contents of this file are subject to POOL Public License 1.0 and later.
* POOL Public License is based on Affero GPL v3 and additional conditions.
* ("License"); You may not use this file except in compliance with the License
* You may obtain a copy of the Affero GPL v3 License at http://www.gnu.org/licenses/agpl.html
* You may obtain a copy of the POOL Public License 1.0 or later at www.wikiocean.net/license/ppl.html
* Software distributed under POOL Public License 1.0 is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
* The Initial Developer of the Original Code is Paritosh Pungaliya (C) 2008. All Rights Reserved.
******************************************************************************
* Objective of the additional terms (license)
* 1) Is to extend the software freedom to freedom to work.
* 2) To ensure that knowledge is free from monopoly of agencies.
* 3) To avoid a situation where big corporate or investor can buy out free software groups and companies and then start milking the communities built around it.
* (this trend can be seen how the freedom is curtailed in companies that get Venture Capital funding.)
******************************************************************************
*/

package  guiregistration;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Stack;
import javax.swing.text.*;

import dbmanager.DBManager;
import utility.Input;
import guireportgenerator.MaxId;
import guiparser.*;

public class HTMLParseLister extends HTMLEditorKit.ParserCallback
{
	public static String start_tag;
    static int TagCount;
    HTML.Tag CurrentTag= null;
    String current_tag;
    public LinkedHashMap<Object,LinkedList<Object>> HtmlTags= new LinkedHashMap<Object, LinkedList<Object>>();
    Stack<Object> CurrunttagSequence= new Stack<Object>();
    boolean isSimpleTagEnd = false;
    String tag_to_insert,ItsParent;
    MaxId max;
    int count = 0;
    
    /**
     * default constructor 
     *
     */
    HTMLParseLister()
    {
    	max = new MaxId();
    	TagCount = Integer.parseInt(max.getMaxId());    	
    }
       
    public LinkedHashMap<Object, LinkedList<Object>> getHash()
    {
    	return HtmlTags;
    }
    /**
     * @overriden method of class HTMLEditorKit.ParserCallback
     * @param data
     * @param pos
     */
    public void handleText(char[] data, int pos) 
    {
       String  TagText=new String(data);  
       
       if(CurrentTag.toString().equalsIgnoreCase("style"))
       {
       		this.createCssObject(TagText);
       }
       else
       {
       		this.createDisplaytextObject(TagText);
       }
    }
    
    /**
     * Creates displaytext object
     * @param dtext
     * @param Tag
     */
    public void createDisplaytextObject(String dtext)
    {
    	LinkedList<Object> displaytextPropList = new LinkedList<Object>();
    	String current_tag = (String)CurrunttagSequence.peek();
    	
    	TagCount++;
    	String Displaytext= "displaytext_"+String.valueOf(TagCount);
    	
    	displaytextPropList.add("type\tdisplaytext\t1");
    	
    	if(dtext.length() <80)
   		{
    		displaytextPropList.add("text\t"+dtext+"\t2");
   	   		HtmlTags.put(Displaytext,displaytextPropList);
   	   		int listsize = HtmlTags.get(current_tag).size()+1;
   	   		HtmlTags.get(current_tag).add("displaytext\t"+Displaytext+"\t"+listsize);
   	   		System.out.println(HtmlTags);
   		}
   		else
   		{
   			String filename = "File_"+String.valueOf(TagCount+1);
   			String DisplaytextFilePath = new String(Input.DISPLAYTEXT_FILES+filename);
   			File DisplaytextFile = new File(DisplaytextFilePath+Input.FILRFORMAT);
   	   		
   	   		if(!DisplaytextFile.exists())
   	   		{
   	   			try {
						if(DisplaytextFile.createNewFile())
						{
							System.out.println("File created");
							
							FileWriter fw =new FileWriter(DisplaytextFile);
							fw.write(dtext.toString());
							fw.close();							
						}
						else
							System.out.println("File not created");
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
   	   		}
   	   		
   	   		String storage = new String("storage_"+String.valueOf(TagCount+1));
   	   		LinkedList<Object> StoragePropList = new LinkedList<Object>();
   	   		StoragePropList.add("type\tstorage\t1");
   	   		StoragePropList.add("path\t"+filename+"\t2");
   	   		HtmlTags.put(storage, StoragePropList);
   	   		
   	   		String report = new String("report_"+String.valueOf(TagCount+2));
   	   		LinkedList<Object> ReportPropList = new LinkedList<Object>();
   	   		ReportPropList.add("type\treport\t1");
   	   		ReportPropList.add("storage\t"+storage+"\t2");
   	   		HtmlTags.put(report, ReportPropList);
   	   		
   	   		displaytextPropList.add("report\t"+report+"\t2");
   	   		HtmlTags.put(Displaytext,displaytextPropList);
   	   		int listsize = HtmlTags.get(current_tag).size()+1;
	   		HtmlTags.get(current_tag).add("displaytext\t"+Displaytext+"\t"+listsize);
	   		
   	   		System.out.println(HtmlTags);
   		}
    }
    
    /**
     * this method creates a css object
     * @param text 
     */  
    public void createCssObject(String text)
    {
    	current_tag = CurrunttagSequence.peek().toString();
    	
    	String [] temparr = text.split("}");
    	System.out.println(text);
    	
    	for(int i=0;i<temparr.length-1;i++)
    	{
    		LinkedList<Object> CssPropList = new LinkedList<Object>();
    		
    		String temp = temparr[i];
    		System.out.println(temp);
    		
    		// classname of css 
    		int ndx = temp.indexOf('{');
    		String ClassName = temp.subSequence(0, ndx).toString().trim();
    		CssPropList.add("type\tcss\t1");
    		CssPropList.add("name\t"+ClassName+"\t2");
    		
    		// actual object of css that's going to be register
    		String CssObjectName = "css_"+TagCount;    		
    		
    		String [] propplist = temp.subSequence(ndx+1, temp.length()).toString().split(";");
    		    		
    		for(int j=0;j<propplist.length-1;j++)
    		{
    			String property[] = propplist[j].trim().split(":");
    			int ref = j+2;
    			CssPropList.add(property[0]+"\t"+property[1]+"\t"+ref);
			}
    		
    		HtmlTags.put(CssObjectName, CssPropList);
    		int listsize = HtmlTags.get(current_tag).size()+1;
    		HtmlTags.get(current_tag).add("css\t"+CssObjectName+"\t"+listsize);
    		System.out.println(HtmlTags);
    		TagCount++;    		
		}
    }
    
    /**
     * @overriden method of class HTMLEditorKit.ParserCallback
     * @param data
     * @param pos
     */
    public void handleComment(char[] data, int pos) 
    {
        String text_data = new String(data);
        System.out.println(current_tag.toString());        
        this.createDisplaytextObject("&lt;!--"+text_data+"--&gt;");       
	}
                
    /**
     * @overriden method of class HTMLEditorKit.ParserCallback
     * @param t
     * @param a
     * @param pos
     */
    public void handleStartTag(HTML.Tag t, MutableAttributeSet a, int pos) 
    {
        CurrentTag =t;
        System.out.println(t.toString());
        
        CurrunttagSequence.push(t+"_"+String.valueOf(TagCount));
        putIntoHashTable(t,a);
        
        if(count == 0)
        {
        	start_tag = (String)CurrunttagSequence.peek();
        	count++;
        }        
    }
    
    /**
     * @overriden method of class HTMLEditorKit.ParserCallback
     * @param t
     * @param pos
     * 
     */
    public void handleEndTag(HTML.Tag t, int pos) 
    {
        System.out.println("Tag end(</" + t.toString() + ">)");
        if(!CurrunttagSequence.isEmpty())
        {
           String temp = CurrunttagSequence.pop().toString();
           if(!CurrunttagSequence.isEmpty())
        	   current_tag = CurrunttagSequence.peek().toString();
                      
           if(!CurrunttagSequence.isEmpty()==true)
           {
        	   ItsParent =CurrunttagSequence.peek().toString();
        	   int listsize = HtmlTags.get(ItsParent).size()+1;
        	   HtmlTags.get(ItsParent).add("tag\t"+temp+"\t"+listsize);
               System.out.println(HtmlTags);
           }
       }
    }
        
    /**
     * @overriden method of class HTMLEditorKit.ParserCallback
     * @param t
     * @param a
     * @param pos
     */
    public void handleSimpleTag(HTML.Tag t, MutableAttributeSet a, int pos)
    {
        CurrentTag=t;
        System.out.println(t.toString());
        String CTag = t+"_"+String.valueOf(TagCount);
        CurrunttagSequence.push(CTag);
        isSimpleTagEnd = true;
        putIntoHashTable(t,a);
        System.out.println("Current TAG AND ITS  LEVEL \t"+t +"::"+(CurrunttagSequence.size()+1));
        String ItsParent=CurrunttagSequence.peek().toString();
        
        LinkedList<Object> list = HtmlTags.get(ItsParent);
        int ref = list.size()+1;           
        HtmlTags.get(ItsParent).add("tag\t"+CTag+"\t"+ref);
        System.out.println(HtmlTags);        
    }
    
    /**
     * @overriden method of class HTMLEditorKit.ParserCallback
     * @param errorMsg
     * @param pos
     */
    public void handleError(String errorMsg, int pos)
    {
    	System.out.println("Parsing error: " + errorMsg + " at " + pos);
    }
   
     /**
     * Puts each tag with its attribute list into hashmap
     * @param t
     * @param a
     */
	
    private void  putIntoHashTable(HTML.Tag t, MutableAttributeSet a)
	{
    	TagCount++;
	    LinkedList<Object> temp_atbtLinkList=new LinkedList<Object>();
	    Enumeration enum1= a.getAttributeNames();
	    int refid = 2;
	    boolean isTypePresent = false;
	    
	    if(enum1.hasMoreElements())
	    {
	    	while(enum1.hasMoreElements())
	        {	    		
	    		Object  atrributeName = enum1.nextElement();
	    		System.out.println(atrributeName);
	    		if(atrributeName.toString().equalsIgnoreCase("type"))
	    		{
	    			isTypePresent = true;
	    		}
	    		
	    		String	atrributeValue=a.getAttribute(atrributeName).toString();
	    		temp_atbtLinkList.add(atrributeName+"\t"+atrributeValue+"\t"+refid);
	    		refid++;
	        }
	    	
	    	if(!isTypePresent)
			{
				temp_atbtLinkList.add(0,"type\tattribute\t1");
			}
	    }  
	    
	    tag_to_insert = CurrunttagSequence.peek().toString();
	    
	    if(temp_atbtLinkList.size() > 0)
	    {
	    	HtmlTags.put("attribute_"+String.valueOf(TagCount), temp_atbtLinkList);
	    	temp_atbtLinkList = new LinkedList<Object>();
	    	temp_atbtLinkList.add("attribute\tattribute_"+String.valueOf(TagCount)+"\t2");
	    	refid++;
	    }
	    
    	temp_atbtLinkList.add(0,"type\t"+t.toString()+"\t1");
    	
    	HtmlTags.put(tag_to_insert,temp_atbtLinkList);
       	System.out.println(HtmlTags);
       	
       	if(isSimpleTagEnd)
       	{
       		CurrunttagSequence.pop();
       		isSimpleTagEnd = false;
       	}
	}
	
	/**
	 * Returns start tag
	 * @return
	 */
	public String getStartTag()
	{
		return start_tag;
	}
	
	
}    

